<?php
include('../cfg/cfg.inc.php');
include('../include/user.class.php');
include('../include/db.inc.php');
session_start();

unset($_SESSION["error"]);
if (isset($_POST['usuario']) && isset($_POST['clave'])) {
    $db = new DbManager();
    $db->connect(DBHOST, DBUSER, DBPWD, true, true, DBNAME, "");
    $us = $_POST['usuario'];
    $cl = $_POST['clave'];
    $en = $_POST['entidad'];
    validaUsuario($us, $cl, $en, $db);
} else {
    header('Location: ../login/');
}

function validaUsuario($usuario, $clave, $entidad, $db) {
    $r = $db->query_select("cllg_user", sprintf("USER_NAME='%s'", $usuario));
    if (count($r) > 0) {
        $u = $r[0];
        $pass = $u["PASSWORD"];
        $clave = md5($clave);
        if ($u['FK_ENTITY'] != $entidad) {
            $_SESSION["error"] = "Entidad invalida para este usuario!";
            header('Location: ../login/');
        } else if ($pass == $clave) {
            $sysUser = new SysUser();
            $sysUser->name = $u['USER_NAME'];
            $sysUser->timeLogon = time();
            $sysUser->lg("ACCESO A APLICACION", NULL);
            $sysUser->entity = $entidad;
            getCicloEntidad($db, $sysUser);
            session_cache_expire(100000);
            $_SESSION['user'] = serialize($sysUser);
            header('Location: ../main.php');
        } else {
            $_SESSION["error"] = "Clave invalida!";
            header('Location: ../login/');
        }
    } else {
        $_SESSION["error"] = "Usuario invalido!";
        header('Location: ../login/');
    }
}

function getCicloEntidad($db, $user) {
    $rs = $db->query_select("cllg_college_cycle", "STATUS=1 AND FK_ENTITY=" . $user->entity);
    if (count($rs) > 0) {
        $rs = $rs[0];
        $user->cycle = $rs["CODE"];
    } else {
        $user->cycle = null;
    }
}

?>